# -*- coding: utf-8 -*-
"""
@Time : 2024/5/4 3:38 PM
@Author: imamhusan
@Des: 描述
"""
from fastapi import APIRouter, Security, Request, Body
from core.WX_PayToolUtil import WX_PayToolUtil
from models.order import Order, OrderDetail
from core.Utils import generate_order_no
from core.Response import success, fail
from schemes.order import OrderData
from core.Auth import verify_token
from models.wx_user import WxUser
from models.goods import Goods
import xmltodict
import os

router = APIRouter(prefix='/order')

wx_pay = WX_PayToolUtil(
    APP_ID=os.getenv('MP_APPID'),
    MCH_ID=os.getenv('MCH_ID'),
    API_KEY=os.getenv('MCH_KEY'),
    NOTIFY_URL='https://class.ozhas.cn/api/v1/order/notify'
)


# 统一下单回调处理
@router.post('/notify', tags=['统一下单回调处理'], description='统一下单回调处理')
async def notify(req: Request):
    try:
        msg = bytes(await req.body()).decode()
        xml_msg = xmltodict.parse(msg)

        result = xml_msg.get('xml')

        if result.get('return_code') == 'SUCCESS' and result.get('result_code') == 'SUCCESS':
            # 支付成功，处理业务逻辑
            out_trade_no = result.get('out_trade_no')
            # TODO：根据商户订单号out_trade_no处理业务逻辑
            # order_id = result.get('attach')
            order = await Order.get(order_no=out_trade_no)
            # 根据需要处理业务逻辑 !!!注意此处要考虑安全问题!!!
            order.state = 1
            await order.save(update_fields=['state'])
            return "<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>"
        else:
            return "<xml><return_code>FAIL</return_code><return_msg>ERROR</return_msg></xml>"
    except Exception as e:
        return fail(msg=str(e))


@router.post('/{order_id}', description='微信支付', dependencies=[Security(verify_token)])
async def payment(req: Request, order_id: int):
    try:
        user_id = req.state.user_id
        user = await WxUser.get_or_none(pk=user_id).values('id', 'openid')
        order = await Order.get_or_none(id=order_id).values('id', 'total_price', 'order_no')

        res = wx_pay.getPayUrl(
            orderid=order['order_no'], openid=user['openid'], goodsPrice=order['total_price'], attach=order['id'])
        return success(data=res, msg='提交订单')
    except Exception as e:
        return fail(msg=str(e))


@router.post('', description='提交订单', dependencies=[Security(verify_token)])
async def submit_order(req: Request, post: OrderData):
    try:
        user_id = req.state.user_id
        data = post.dict()
        card_list = data['cardList']
        total_count = 0
        total_price = 0
        data['user_id'] = user_id
        data['order_no'] = generate_order_no(ln=4)

        goods_list = await Goods.filter(id__in=[item['id'] for item in card_list]).values()
        # goods_dict = {goods.id: goods for goods in goods_list}

        for index, item in enumerate(card_list):
            total_count += item['pro_count']
            # goods = goods_dict.get(item['id'])
            # total_price += item['pro_count'] * goods.price
            total_price += item['pro_count'] * goods_list[index].get('price')

        data['total_count'] = total_count
        data['total_price'] = total_price

        new_order = await Order.create(**data)

        order_detail = [OrderDetail(
            price=item['price'],
            goods_id=item['id'],
            pro_count=item['pro_count'],
            order_id=new_order.pk
        ) for item in card_list]

        await OrderDetail.bulk_create(order_detail)

        return success(data=new_order, msg='获取成功')
    except Exception as e:
        return fail(str(e))


@router.put('/{orderid}/{state}', description='修改订单状态', dependencies=[Security(verify_token)])
async def update_order_state(orderid: int, state: int):
    try:
        update_ok = await Order.filter(pk=orderid).update(state=state)
        if update_ok:
            return success(msg='订单状态修改成功')
        return fail(msg='订单状态修改失败')
    except Exception as e:
        return fail(str(e))


@router.put('/{state}', description='修改订单状态', dependencies=[Security(verify_token)])
async def update_order_state(state: int, ids: list[int] = Body(..., embed=True)):
    try:
        update_ok = await Order.filter(id__in=ids).update(state=state)
        if update_ok:
            return success(msg=f'{update_ok}_条订单状态修改成功')
        return fail(msg='订单状态修改失败')
    except Exception as e:
        return fail(str(e))


@router.get('/{state}', description='获取订单列表', dependencies=[Security(verify_token)])
async def get_order_list(req: Request, state: int):
    try:
        lan = req.headers.get('lan', 'uy')
        user_type = req.state.user_type

        where = {"state": state}
        if user_type == 'mp':
            where['user_id'] = req.state.user_id

        orders = await Order.filter(**where).prefetch_related('order_details', 'user')

        result = [
            {
                **dict(item),
                'user': await item.user,
                'detail': await item.order_details.all().values(
                    'id', 'price', 'pro_count', 'goods_id', image='goods__image', title=f'goods__title_{lan}')}
            for item in orders]

        return success(data=result, msg='获取成功')

    except Exception as e:
        return fail(str(e))